package nutz.cyx.module;

import nutz.cyx.bean.User;
import nutz.cyx.system.SystemParam;
import nutz.cyx.util.DbUtil;
import org.nutz.dao.Cnd;
import org.nutz.dao.impl.NutDao;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Attr;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;


import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;


/**
 * Created by chenyingxi on 2014/5/19.
 */
@IocBean
@At("/user")
public class UserModule {
    @Inject
    NutDao nutDao;

    @At
    @Ok("jsp:view.user.userlist")
    public Object userlist() {
        Sql sql = nutDao.sqls().create("tablelist");
        sql.setPager(nutDao.createPager(1, SystemParam.pageSize));
        sql.vars().set("table", "user");
        return DbUtil.querySqlHelper(nutDao, sql, User.class);

    }

    @At
    public boolean login(@Param("username") String name, @Param("password") String password, HttpSession session) {
        if (Strings.isEmpty(name) || Strings.isEmpty(password)) return false;
        name = name.trim().intern();
        password = password.trim().intern();
        User user = nutDao.fetch(User.class, Cnd.where("username", "=", name).and("password", "=", password));
        if (user == null) return false;
        session.setAttribute("me", user);
        return true;
    }

    @At
    @Ok(">>:/")
    public void loginOut(HttpSession session) {
        session.invalidate();
    }

    @At
    public User me(@Attr("me") User user) {
        return user;
    }

    @At("/ping")
    public Object ping() {
        return new Date();
    }
}
